package com.test.codec.rsa;


import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.*;

/**
 * @Description: RSA采用 特定的签名方式，
 * @Author: yangzhiwei
 * @Date: 2020/11/19 13:38
 */
public class RSASign {
    /**
     * MD5withRSA
     * SHA1withRSA
     * SHA256withRSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * As you know ，RSA is
     * @param args
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws SignatureException
     */


    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchPaddingException {
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        System.out.println(kpGen);
        kpGen.initialize(1024);

        KeyPair keyPair = kpGen.generateKeyPair();

        PrivateKey sk = keyPair.getPrivate();
        System.out.println(sk.getAlgorithm());

        PublicKey pk = keyPair.getPublic();
        System.out.println(pk);

        byte[] messge = "hello, I am Bob !".getBytes(StandardCharsets.UTF_8);

        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(sk);
        signature.update(messge);
        byte[] signed = signature.sign();
        System.out.println(String.format("signature: %x", new BigInteger(1, signed)));
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,sk);

        System.out.println(sk);

        Signature v = Signature.getInstance("MD5withRSA");
        v.initVerify(pk);
        v.update(messge);
        boolean valid = v.verify(signed);
        System.out.println("valid?" + valid);
    }
}
